import 'package:flutter_blue_plus/flutter_blue_plus.dart';

class Communicator {
  Communicator(this.writeCharacteristic);
  bool _waitingSend = false;
  int lastTimestamp = 0;

  BluetoothCharacteristic writeCharacteristic;

  void sendData(List<int> data, {bool force = false}) {
    if (force) {
      print('发送数据到设备 ${writeCharacteristic.uuid} $data');
      writeCharacteristic.write(data);
      lastTimestamp = DateTime.now().millisecondsSinceEpoch;
      return;
    }
    if (DateTime.now().millisecondsSinceEpoch - lastTimestamp > 50) {
      print('发送数据到设备 ${writeCharacteristic.uuid} $data');
      writeCharacteristic.write(data);
      lastTimestamp = DateTime.now().millisecondsSinceEpoch;
    }
  }

  void sendDataLoop(List<int> data, int errortimes, int delaymillsecond) {
    Duration delay = Duration(milliseconds: delaymillsecond);
    Future.delayed(delay, () {
      if (_waitingSend && errortimes > 0) {
        sendDataLoop(data, errortimes - 1, delaymillsecond);
        writeCharacteristic.write(data);
      }
    });
  }
}
